package com.changgou.filter;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;

/**

 新建过滤器类AuthorizeFilter,对请求进行过滤

 业务逻辑：

 1）判断当前请求是否为登录请求，是的话，则放行

 2)   判断cookie中是否存在信息, 没有的话，拒绝访问

 @Service
 public class AuthService {

 @Autowired
 private StringRedisTemplate stringRedisTemplate;

 //从cookie中获取jti
 public String getJtiFromCookie(ServerHttpRequest request) {
 HttpCookie httpCookie = request.getCookies().getFirst("uid");
 if (httpCookie !=null){
 String jti = httpCookie.getValue();
 return jti;
 }
 return null;
 }

 //从redis中获取jwt
 public String getJwtFromRedis(String jti) {

 String jwt = stringRedisTemplate.boundValueOps(jti).get();
 return jwt;
 }
 }


 3）判断redis中令牌是否过期，过期的话，拒绝访问

 4）判断请求头上是否存在令牌，不存在，拒绝访问


 **/

@Component
public class AuthFilter implements GlobalFilter, Ordered {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        URI uri = request.getURI();
        String path = uri.getPath();
        if ("/api/oauth/login".equals(path)){
            // 放行
            return chain.filter(exchange);
        }
        HttpCookie httpCookie = request.getCookies().getFirst("uid");
        if (httpCookie!=null){
            String value = httpCookie.getValue(); // 拿到了cookie  cookie中保存的是jti
            if (StringUtils.isEmpty(value)){
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
            else {
                String token = stringRedisTemplate.boundValueOps(value).get();
                if (StringUtils.isEmpty(token)){
                    response.setStatusCode(HttpStatus.UNAUTHORIZED);
                    return response.setComplete();
                }
                request.mutate().header("Authorization","Bearer "+token);
                return chain.filter(exchange);
            }
        }

        return null;

    }

    @Override
    public int getOrder() {
        return 0;
    }
}
